from re import match

from libs.luffy_response import LuffyResponse
from rest_framework.decorators import action
from rest_framework.viewsets import ViewSet, ModelViewSet

from .serializer import LuffyUserSerializer, UserRegisterSerializer
from .models import LuffyUserModel

# Create your views here.


class LoginViewSet(ViewSet):
    @action(["POST"], False)
    def login(self, request, *args, **kwagrs):
        ser = LuffyUserSerializer(data=request.data)
        if ser.is_valid():
            username = ser.context.get("user").username
            token = ser.context.get("token")
            refresh = ser.context.get("refresh")
            return LuffyResponse(username=username, token=token, refresh=refresh)
        else:
            return LuffyResponse(code=4000, msg=ser.errors)

    @action(['GET'], False)
    def check_mobile(self, request):
        mobile = request.GET.get("mobile")
        if not match("^1[3-9][0-9]{9}", mobile):
            return LuffyResponse(4000, "手机号不合法！")
        try:
            LuffyUserModel.objects.get(mobile=mobile)
            return LuffyResponse(data="已存在")
        except Exception:
            return LuffyResponse(data="不存在")


class RegisterViewSet(ModelViewSet):
    queryset = LuffyUserModel.objects.all()
    serializer_class = UserRegisterSerializer

    def create(self, request, *args, **kwargs):
        response = super().create(request, *args, **kwargs)
        username = response.data.get("username")
        return LuffyResponse(msg="注册成功！",username=username)